package ws

import (
	"common_demo/pkg/logger"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

type WsHandler struct {
	wsUpgrader *websocket.Upgrader
}

func NewWsHandler() *WsHandler {
	return &WsHandler{
		wsUpgrader: &websocket.Upgrader{
			ReadBufferSize:  1024,
			WriteBufferSize: 1024,
			CheckOrigin: func(r *http.Request) bool {
				return true
			},
		},
	}
}

func (handler *WsHandler) Ws(ctx *gin.Context) {
	conn, err := handler.wsUpgrader.Upgrade(ctx.Writer, ctx.Request, nil)
	if err != nil {
		logger.Errorf("failed to upgrade to websocket, error: %s", err.Error())
		return
	}
	defer conn.Close()

	logger.Debugf("%s connected to websocket...", ctx.RemoteIP())

	for {
		msgType, msg, err := conn.ReadMessage()
		if err != nil {
			if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
				logger.Debugf("client %s sent close frame", ctx.RemoteIP())
				break
			}
			logger.Errorf("failed to read message, error: %s", err.Error())
			break
		}

		logger.Debugf("received message: %s", string(msg))

		resp := []byte("response: " + string(msg))
		if err = conn.WriteMessage(msgType, resp); err != nil {
			logger.Errorf("failed to send message, error: %s", err.Error())
			break
		}
	}
}
